﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LevsSimulator
{
    public class GenericReceivedInstrumentState
    {
        /// <summary>
        /// 内窥镜已连接？
        /// </summary>
        public bool EndoscopicConnected { get; set; }

        /// <summary>
        /// 耗材序列号
        /// </summary>
        public string HcSerialNo { get; set; }

        /// <summary>
        /// 耗材使用时间
        /// </summary>
        public int? HcUsedTime { get; set; }

        /// <summary>
        /// 视频旋转角度
        /// </summary>
        public byte VideoRotate { get; set; }

        /// <summary>
        /// LED 亮度
        /// </summary>
        public byte? LedBrightness { get; set; }

        /// <summary>
        /// 错误代码
        /// </summary>
        public byte ErrorCode { get; set; }

        public DateTime FactoryTime { get; set; }

        public byte[] EncodePacket()
        {
            var list = new List<byte>();
            // 内窥镜连接状态
            list.Add((byte)(EndoscopicConnected ? '1' : '0'));
            // 错误状态
            list.Add((byte)(ErrorCode + '0'));
            // POSIX时间(秒）10位
            var secStr = ((long)(FactoryTime - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
            list.AddRange(AsciiToBytes(secStr));
            // 图像翻转指令
            list.Add(VideoRotate);
            // 耗材十六进制序列号值
            if (string.IsNullOrEmpty(HcSerialNo))
            {
                list.AddRange(FfBytes(6));
            }
            else
            {
                list.AddRange(AsciiToBytes(HcSerialNo));
            }
            // 下位机耗材模块运行时间
            if (!HcUsedTime.HasValue)
            {
                list.AddRange(FfBytes(2));
            }
            else
            {
                list.AddRange(AsciiToBytes(HcUsedTime.Value.ToString().PadLeft(2, '0')));
            }

            // LED灯亮度等级
            list.Add((byte)((LedBrightness ?? 0) + '0'));
            return list.ToArray();
        }

        private byte[] AsciiToBytes(string str)
        {
            return Encoding.ASCII.GetBytes(str);
        }

        private static byte[] FfBytes(int count)
        {
            var bytes = new byte[count];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = 0xFF;
            }

            return bytes;
        }
    }
}